import React, { useEffect, useState } from 'react'
import { Breadcrumb } from 'antd';
import { Link, useLocation, useHistory } from 'react-router-dom';
import { findOneRouter } from '../../routes';

const IMBread = () => {
    const location = useLocation()
    const history = useHistory()
    const [breads, setBreads] = useState<any[]>([])
    const findCanJump = (url: string) => {
        const router = findOneRouter(url)
        return router?.CName ? true : false
    }
    useEffect(() => {
        // 这里因为动态路由无法拿到 所以正则将动态路由变为一般路由
        const reg = /(\/\d)/g
        if (reg.test(location.pathname)) {
            const index = reg.lastIndex - 1
            location.pathname = index > -1 ? location.pathname.substring(0, index) : location.pathname
        }
        // 这里是判断router是否存在 不存在的话就跳转404
        if (!findOneRouter(location.pathname)) {
            history.push('/404')
            return
        }
        // router存在就生成面包屑
        const pathSnippets = location.pathname.split('/').filter(i => i);
        console.log(pathSnippets)
        const extraBreadcrumbItems = pathSnippets.map((_, index) => {
            let url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
            // 这里因为动态路由无法拿到 所以正则将动态路由变为一般路由 同上
            const reg = /(\/\d)/g
            if (reg.test(url)) {
                const index = reg.lastIndex - 1
                url = index > -1 ? url.substring(0, index) : url
            }
            const name = findOneRouter(url).name
            return (
                <Breadcrumb.Item key={url}>
                    {
                        findCanJump(url) ? <Link to={url}>{name}</Link> : name
                    }
                </Breadcrumb.Item>
            );
        });
        setBreads(extraBreadcrumbItems)
    }, [location])
    return <div><Breadcrumb>{breads}</Breadcrumb></div>
}

export default IMBread